//
//  KLEntrustSecondMasterVC.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 17/3/22.
//  Copyright © 2017年 陈宾鹏. All rights reserved.
//

#import "KLEntrustSecondMasterVC.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "BeeCloud.h"
#import "HemaFunction.h"
#import "SSKeychain.h"
#import "KLRechargeViewController.h"
#import "BuleFuction.h"
#import "NSData+hex.h"
#import <AddressBookUI/ABPeoplePickerNavigationController.h>
#import <AddressBook/ABPerson.h>
#import <AddressBookUI/ABPersonViewController.h>

@interface KLEntrustSecondMasterVC ()<UIAlertViewDelegate,UIActionSheetDelegate,BeeCloudDelegate,ABPeoplePickerNavigationControllerDelegate>
{
    NSString *totalfee;
}
@property(nonatomic,strong) NSString *money;
@property(nonatomic,strong) NSString *trade_no;

@property (weak, nonatomic) IBOutlet UITextField *mobileField;
@property (weak, nonatomic) IBOutlet UIButton *addressList;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;

@end

@implementation KLEntrustSecondMasterVC
-(void)viewWillAppear:(BOOL)animated{
    [KLHelp hideAllHUDsForView:self.view animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"授权二级锁主";
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    
    self.mobileField.keyboardType = UIKeyboardTypeNumberPad;
    self.confirmBtn.backgroundColor = [KLHelp mainBlueColor];
    self.confirmBtn.layer.masksToBounds = YES;
    self.confirmBtn.layer.cornerRadius = 5;
}-(void)doBack:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)confirmEntrust:(UIButton *)sender {
    [self.mobileField endEditing:YES];
    BOOL isValid = [HemaFunction xfunc_isMobileNumber:self.mobileField.text];
    if(isValid){
        [KLHelp showHUDAddedTo:self.view animated:YES];
        [KLHttpAPI requestGetGrant_lock_priceWithCompletionHandler:^(MKNetworkOperation *operation) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSLog(@"operation:%@",operation.responseString);
            NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
            if(isSuccess.integerValue == 1){
                NSString *price = [NSString stringWithFormat:@"价格:¥%@",[operation.responseJSON objectForKey:@"infor"]];
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"正在进行委托授权" message:price delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alert show];
            }else{
                [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
            }
        } errorHandler:^(NSString *error) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [KLHelp showTextHUDforView:self.view text:error];
        }];
    }else{
        [KLHelp showTextHUDforView:self.view text:@"请输入正确手机号"];
    }
}

#pragma mark - UIAlertDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        totalfee = [alertView.message substringFromIndex:4];
        NSLog(@"totalfee:%@,%zd",totalfee,totalfee.length);
        //判断当前余额是否充足
//        NSString *amount = [[NSUserDefaults standardUserDefaults] objectForKey:@"feeaccount"]; // 服务器返回数据不对
        NSString *amount = @"100"; // 这里写个死数据
        
        NSLog(@"amount:%zd",amount);
        if(amount.doubleValue < totalfee.doubleValue){
            self.money = [NSString stringWithFormat:@"%.f",totalfee.doubleValue * 100];
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"当前余额不足" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"充值",@"在线支付", nil];
            [sheet showInView:self.view];
        }else{
            //获取keychain里的所有公钥
            NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
            NSDictionary *publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
            NSString *publicStr = [publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]];
            if(publicStr.length == 0){
                [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
                return ;
            }
            NSString *aesKey = [KLHelp getUserSixTeenRandomAESKey];
            NSData *rsaData = [BuleFuction packChildkeyToData:publicStr mobileStr:[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"] startTime:@"000000000000" endTime:@"000000000000" commondCode:@"0" userAESKey:aesKey];
            NSString *rsaKey = [rsaData convertDataToHexStr:rsaData];
            
            [KLHelp showHUDAddedTo:self.view animated:YES];
            [KLHttpAPI distributeChild_keyWithLockID:[self.currentLockInfo objectForKey:@"id"] mobile:self.mobileField.text startdate:@"0000-00-00 00:00:00" enddate:@"0000-00-00 00:00:00" totalfee:totalfee rsa_data:rsaKey style:[self.currentLockInfo objectForKey:@"type"] from_key_id:[self.currentLockInfo objectForKey:@"keyid"] AESkey:aesKey power:@"02" updatetime:@"0" token:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] commondCode:@"a1" completionHandler:^(MKNetworkOperation *operation) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
            } errorHandler:^(NSString *error) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                [KLHelp showTextHUDforView:self.view text:error];
            }];
            
        }
    }
}

#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%zd",buttonIndex);
    if(buttonIndex == 0){//充值
        KLRechargeViewController *rechargeVC = [[KLRechargeViewController alloc]init];
        [self.navigationController pushViewController:rechargeVC animated:YES];
    }else if(buttonIndex == 1){//在线支付
        [KLHelp showHUDAddedTo:self.view animated:YES];
        //设置支付代理
        [BeeCloud setBeeCloudDelegate:self];
        //充值
        [self recharge];
    }
}

-(void)recharge{
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"localString:%@",locationString);
    
    //支付请求
    [BeeCloud initWithAppID:@"1e70e317-1286-490b-ad3b-3d56f8f2e0a0" andAppSecret:@"caf7da3a-1b60-499c-920c-5d0c2008693a"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.money,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"], nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = PayChannelAliApp; //支付渠道
    payReq.title = @"KISSLOCK委托二级锁主在线支付";//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@",self.money];//订单价格
    self.trade_no = [NSString stringWithFormat:@"0003%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];//商户自定义订单号
    payReq.billNo = self.trade_no;
    NSLog(@"trade_no:%@",self.trade_no);
    payReq.scheme = @"prefsGuoYangKissLock";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BCPay回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    [KLHelp hideAllHUDsForView:self.view animated:YES];
    if(resp.type == BCObjsTypePayResp){
        // 支付请求响应
        BCPayResp *tempResp = (BCPayResp *)resp;
        if (tempResp.resultCode == 0) {
            NSLog(@"支付情况：%@",resp.resultMsg);
            [KLHttpAPI payoffSuccessWithKeytype:@"1" total_fee:self.money trade_no:self.trade_no completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"充值返回数据：%@",operation.responseString);
                NSDictionary *dic = operation.responseJSON;
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    //获取keychain里的所有公钥
                    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
                    NSDictionary *publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
                    NSString *publicStr = [publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]];
                    if(publicStr.length == 0){
                        [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
                        return ;
                    }
                    NSString *aesKey = [KLHelp getUserSixTeenRandomAESKey];
                    NSData *rsaData = [BuleFuction packChildkeyToData:publicStr mobileStr:[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"] startTime:@"000000000000" endTime:@"000000000000" commondCode:@"0" userAESKey:aesKey];
                    NSString *rsaKey = [rsaData convertDataToHexStr:rsaData];
                    
                    [KLHelp showHUDAddedTo:self.view animated:YES];
                    [KLHttpAPI distributeChild_keyWithLockID:[self.currentLockInfo objectForKey:@"id"] mobile:self.mobileField.text startdate:@"0000-00-00 00:00:00" enddate:@"0000-00-00 00:00:00" totalfee:totalfee rsa_data:rsaKey style:[self.currentLockInfo objectForKey:@"type"] from_key_id:[self.currentLockInfo objectForKey:@"keyid"] AESkey:aesKey power:@"02" updatetime:@"0" token:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] commondCode:@"a1" completionHandler:^(MKNetworkOperation *operation) {
                        [KLHelp hideAllHUDsForView:self.view animated:YES];
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    } errorHandler:^(NSString *error) {
                        [KLHelp hideAllHUDsForView:self.view animated:YES];
                        [KLHelp showTextHUDforView:self.view text:error];
                    }];
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"充值失败"];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:@"网络波动，充值失败"];
            }];
            
        } else {
            //支付取消或者支付失败
            NSLog(@"支付取消或失败结果信息:resultMsg：%@, errDetail：%@, type：%zd, resultCode：%zd",tempResp.resultMsg,tempResp.errDetail,tempResp.request.type,tempResp.resultCode);
        }
    }
}

#pragma mark - 打开通讯录
- (IBAction)openAddressList:(UIButton *)sender {
    [KLHelp showHUDAddedTo:self.view animated:YES];
    ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
    nav.peoplePickerDelegate = self;
    
    //这个变量用于记录授权是否成功，即用户是否允许我们访问通讯录
    int __block tip=0;
    //声明一个通讯簿的引用
    ABAddressBookRef addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if (!greanted) {
                tip=1;
            }else{
                if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
                    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
                }
                [self presentViewController:nav animated:YES completion:nil];
                [KLHelp hideAllHUDsForView:self.view animated:YES];
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
    
}

//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    self.mobileField.text = phoneNO;
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.mobileField endEditing:YES];
}
@end
